import { Context } from 'koa';
import { ApiResponse } from '@/types';

/**
 * 成功响应
 */
export function success<T>(ctx: Context, data?: T, message: string = '操作成功'): void {
  const response: ApiResponse<T> = {
    success: true,
    data,
    message,
  };
  ctx.status = 200;
  ctx.body = response;
}

/**
 * 创建成功响应
 */
export function created<T>(ctx: Context, data?: T, message: string = '创建成功'): void {
  const response: ApiResponse<T> = {
    success: true,
    data,
    message,
  };
  ctx.status = 201;
  ctx.body = response;
}

/**
 * 错误响应
 */
export function error(
  ctx: Context,
  message: string = '操作失败',
  code: number = 400,
  errors?: any[],
): void {
  const response: ApiResponse = {
    success: false,
    message,
    code,
    errors,
  };
  ctx.status = code;
  ctx.body = response;
}

/**
 * 未授权响应
 */
export function unauthorized(ctx: Context, message: string = '未授权'): void {
  error(ctx, message, 401);
}

/**
 * 禁止访问响应
 */
export function forbidden(ctx: Context, message: string = '禁止访问'): void {
  error(ctx, message, 403);
}

/**
 * 未找到响应
 */
export function notFound(ctx: Context, message: string = '资源未找到'): void {
  error(ctx, message, 404);
}

/**
 * 服务器错误响应
 */
export function serverError(ctx: Context, message: string = '服务器内部错误'): void {
  error(ctx, message, 500);
}

/**
 * 分页响应
 */
export function paginated<T>(
  ctx: Context,
  data: T[],
  total: number,
  page: number,
  pageSize: number,
  message: string = '查询成功',
): void {
  const response: any = {
    success: true,
    data,
    message,
    pagination: {
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    },
  };
  ctx.status = 200;
  ctx.body = response;
}


